package com.zero.zerolivewallpaper;


import static com.zero.zerolivewallpaper.Constants.PREF_BACKGROUND;
import static com.zero.zerolivewallpaper.Constants.SERVICE_NAME;

import android.app.Activity;
import android.app.WallpaperInfo;
import android.app.WallpaperManager;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.widget.Toast;

import com.zero.zerolivewallpaper.async.MyAsync;
import com.zero.zerolivewallpaper.async.WallpaperDownloader;
import com.zero.zerolivewallpaper.data.CatalogItem;
import com.zero.zerolivewallpaper.utils.StorageHelper;
import com.zero.zerolivewallpaper.wallpaper.BackgroundHelper;
import com.zero.zerolivewallpaper.wallpaper.MyWallpaperService;
import io.flutter.plugin.common.MethodChannel;

import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.HashMap;
import java.util.Map;


@SuppressWarnings("SameParameterValue")
public class Utils {

    // Get string between to string (excluded)
    public static String getBetweenStrings(String text, String textFrom, String textTo) {

        String result = text.substring(
                text.indexOf(textFrom) + textFrom.length()
        );

        // Cut the excessive ending of the text:
        result = result.substring(0, result.indexOf(textTo));

        return result;
    }

    // Check if sensor is available
    public static boolean sensorsAvailable(Context context) {
        SensorManager sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);

        if (sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR) != null) {
            return true;
        }

        if (sensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY) != null) {
            return true;
        }

        return sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) != null && sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD) != null;
    }

    // Open system live wallpaper setter
    public static void openLWSetter(Context context) {
        Intent intent = new Intent(WallpaperManager.ACTION_CHANGE_LIVE_WALLPAPER);
        intent.putExtra(WallpaperManager.EXTRA_LIVE_WALLPAPER_COMPONENT, new ComponentName(context, MyWallpaperService.class));
        try {
            context.startActivity(intent);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(context, "打开系统动态壁纸设置错误", Toast.LENGTH_LONG).show();
        }
    }

    private static final double SPACE_KB = 1024;
    private static final double SPACE_MB = 1024 * SPACE_KB;
    private static final double SPACE_GB = 1024 * SPACE_MB;
    private static final double SPACE_TB = 1024 * SPACE_GB;

    public static String bytes2String(long sizeInBytes) {

        NumberFormat nf = new DecimalFormat();
        nf.setMaximumFractionDigits(1);
        nf.setMinimumFractionDigits(1);

        try {
            if (sizeInBytes < SPACE_KB) {
                return nf.format(sizeInBytes) + " Byte(s)";
            } else if (sizeInBytes < SPACE_MB) {
                return nf.format(sizeInBytes / SPACE_KB) + " KB";
            } else if (sizeInBytes < SPACE_GB) {
                return nf.format(sizeInBytes / SPACE_MB) + " MB";
            } else if (sizeInBytes < SPACE_TB) {
                return nf.format(sizeInBytes / SPACE_GB) + " GB";
            } else {
                return nf.format(sizeInBytes / SPACE_TB) + " TB";
            }
        } catch (Exception e) {
            return sizeInBytes + " Byte(s)";
        }

    }


    // Start wallpaper setting routine + interface
    public static void setWallpaper(Activity activity, SharedPreferences sharedPreferences, CatalogItem catalogItem) throws IOException {
        final WallpaperManager wallpaperManager = WallpaperManager.getInstance(activity);
    
        if(catalogItem.getLive()) {
            final WallpaperInfo wallpaperInfo = wallpaperManager.getWallpaperInfo();

            sharedPreferences.edit().putString(PREF_BACKGROUND, catalogItem.getId()).apply();
            boolean zeroAsLive = true;

            // Check if Zero is the current live wallpaper
            if (wallpaperInfo == null) {
                zeroAsLive = false;
            } else {
                if (!wallpaperInfo.getServiceName().equals(SERVICE_NAME)) {
                    zeroAsLive = false;
                }
            }

            if (!zeroAsLive) {
                // Show live-wallpaper preview
                openLWSetter(activity);
            } else {
                Toast.makeText(activity, "壁纸已更改", Toast.LENGTH_SHORT).show();
            }
        } else {
            File layerList = StorageHelper.getBackgroundFolder(catalogItem.getId(), activity);
            if(layerList.isDirectory() && layerList.listFiles() != null && layerList.listFiles().length > 0) {
                File imgFile = layerList.listFiles()[0];
                Bitmap bitmap =  BackgroundHelper.decodeScaledFromFile(imgFile);

                if(bitmap != null) {
                    // 获取屏幕的宽度和高度
                    DisplayMetrics dm = new DisplayMetrics();
                    activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
                    int width = dm.widthPixels;
                    int height = dm.heightPixels;
                    wallpaperManager.suggestDesiredDimensions(width, height);
                    wallpaperManager.setBitmap(bitmap);

                    Toast.makeText(activity, "壁纸设置成功", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    public static void downloadWallpaper(Activity activity, MethodChannel channel, final CatalogItem item) {
        // Download
        new WallpaperDownloader(activity, item)
                .setListener(new MyAsync.MyAsyncInterface() {
                    @Override
                    public  void onProgress(Integer percent, Integer  downloadedBytes, Integer totalBytes , Bundle extra) {
                        Map<String, Object> param = new HashMap<>();
                        param.put("percent", percent);
                        param.put("downloadedBytes", downloadedBytes);
                        param.put("totalBytes", totalBytes);
                        param.put("id", item.getId());
                        channel.invokeMethod("downloadWallpaperProgress", param);
                    }
                    @Override
                    public void onCompleted(int id, Bundle extra) {
                        Map<String, Object> param = new HashMap<>();
                        param.put("id", item.getId());
                        channel.invokeMethod("downloadWallpaperCompleted", param);
                    }
                    @Override
                    public void onFailed(int id, Bundle extra) {
                        Map<String, Object> param = new HashMap<>();
                        param.put("id", item.getId());
                        channel.invokeMethod("downloadWallpaperFailed",param);
                    }
                })
                .execute();
    }
}
